package cn.gov.pbc.dream.service.impl;

import cn.gov.pbc.dream.service.IFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service("iFileService")
@Slf4j
public class FileServiceImpl implements IFileService {

    @Override
    public String uploadSingleFile(MultipartFile file, String destPath) {
        if(file == null){
            return null;
        }
        String originFilename = file.getOriginalFilename();
        String ext = originFilename.substring(originFilename.lastIndexOf(".") + 1);

        String destFilename = UUID.randomUUID().toString() + "." + ext;

        File fileDir = new File(destPath);
        if(!fileDir.exists()){
            fileDir.setWritable(true);
            fileDir.mkdirs();
        }
        File targetFile = new File(destPath, destFilename);

        try {
            file.transferTo(targetFile);
        } catch (IOException e) {
            log.error(e.getMessage());
            return null;
        }
        return targetFile.getName();
    }
}
